leetcode Word Search

word search

word search

link
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

For example,
Given board =

[
[‘A’,’B’,’C’,’E’],
[‘S’,’F’,’C’,’S’],
[‘A’,’D’,’E’,’E’]
]
word = “ABCCED”, -> returns true,
word = “SEE”, -> returns true,
word = “ABCB”, -> returns false.

题目大意:
给定一个二维字符数组,找出数组中是否存在某个单词,移动方向为上下左右。

解法:
显然这是一个深度优先搜索加回溯的算法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Solution {
public:
bool exist(vector<vector<char>>& board, string word){
int row = board.size();
int col = board[0].size();

vector<vector<bool> > visited(row, vector<bool>(col, false));

for(int i = 0 ; i < row; ++i)
for(int j = 0; j < col; ++j)
if( dfs(board, word, 0, i, j, visited) )
return true;

return false;
}

bool dfs(vector<vector<bool> > &matrix, string& str, int index, int x, int y, vector<vector<bool> >& flag){
if(index == str.size())
return true;
//越界
if(x<0 || x >= matrix.size() || y<0|| y >= matrix[0].size())
return false;
//不相等
if(matrix[x][y] != str[index])
return false;
//已经访问过
if(flag[x][y])
return false;


flag[x][y] = true;

bool ret = dfs(matrix, str, index +1, x+1, y, flag) ||
dfs(matrix, str, index +1, x -1, y, flag) ||
dfs(matrix, str, index +1, x, y-1, flag)||
dfs(matrix, str, index +1, x, y+1, flag);

flag[x][y] = false;

return ret;
}
};

参考文章:
http://blog.csdn.net/worldwindjp/article/details/18041225
http://www.2cto.com/kf/201412/359314.html